<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="../css/reset.css">
    <style>
        .clock-show {
            width: min-content;
            margin: 50px auto;
            text-align: center;
        }

        .clock-time {
            height: 140px;
            font-family: "clockIcon";
            line-height: 140px;
            font-size: 100px;
        }

        .clock-time span {
            font-size: 60px;
        }

        .clock-date {
            height: 40px;
            line-height: 30px;
            font-size: 16px;
        }

        .clock-date button {
            padding: 5px 10px;
        }


        @font-face {
            font-family: "clockIcon";
            src: url('../font/clockicons.woff2');
        }
    </style>
</head>

<body>
    <div class="clock-show">
        <div class="clock-time">
            00:00<span>.00</span>
        </div>
        <div class="clock-date">
            <button class="start">开始</button>
            <button class="pause">暂停</button>
            <button class="reset">重置</button>
        </div>
    </div>
</body>
<script>
    // document.getElementsByClassName(className)  在文档中获取对应class名的元素
    // 返回值: 返回一个由获取元素形成的数组(伪数组/集合) 
    // var result = document.getElementsByClassName("clock-time");
    // console.log(result);
    // console.log(result[0]);  //对应下标取值

    // 获取元素 并将元素从数据取出
    var clockTime = document.getElementsByClassName("clock-time")[0];
    var start = document.getElementsByClassName("start")[0];
    var pause = document.getElementsByClassName("pause")[0];
    var reset = document.getElementsByClassName("reset")[0];

    var timer = null;
    var count = 0;
    var isStart = false; // 声明一个全局变量 记录秒表的 启停 状态 (启动:true 停止:false(默认))

    start.onclick = function () {
        // 每次点击都会开启一个新的计时器  => 变量timer只能记录最后一个 (之前的就无法被清除)
        // 已经启动就不要再启动新的

        if (isStart) return false;  // 每次点击先判断  => 如果计时器已经启动  则不在执行后续代码

        isStart = true; // 如果没有启动  本次点击将会启动一个计时器 

        timer = setInterval(function () {
            count += 10;

            var ms = count % 1000 / 10;  //毫秒的百位和十位
            var sec = parseInt(count / 1000) % 60; // 不满一分钟的秒数
            var min = parseInt(parseInt(count / 1000) / 60) % 60; // 不满一小数的秒数

            // console.log(count, min, sec, ms);

            clockTime.innerHTML = `${beautify(min)}:${beautify(sec)}<span>.${beautify(ms)}</span>`;

        }, 10)

    }

    pause.onclick = function () {
        clearInterval(timer);
        isStart = false;
    }




    function beautify(num) {
        if (isNaN(num)) {
            var err = new Error("Please pass in a number");
            throw err;
        }
        return num < 10 ? "0" + num : num;
    }








</script>

</html>